package com.yilin.commons.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {


    private FileUtils() {
    }


    /**
     * @Desc 查询当前路径下的所有文件夹(不包含子文件夹)
     * @Param
     */
    public static ArrayList<String> Dir(File dirFile) {
        ArrayList<String> dirStrArr = new ArrayList<String>();
        if (dirFile.exists()) {
            // 直接取出利用listFiles()把当前路径下的所有文件夹、文件存放到一个文件数组
            File files[] = dirFile.listFiles();
            for (File file : files) {
                // 如果传递过来的参数dirFile是以文件分隔符，也就是/或者\结尾，则如此构造
                if (dirFile.getPath().endsWith(File.separator)) {
                    dirStrArr.add(dirFile.getPath() + file.getName());
                } else {
                    // 否则，如果没有文件分隔符，则补上一个文件分隔符，再加上文件名，才是路径
                    dirStrArr.add(dirFile.getPath() + File.separator
                            + file.getName());
                }
            }
        }
        return dirStrArr;
    }


    /**
     * @Desc 递归遍历路径下所有的文件
     * @Param
     */
    public static List<String> DirAll(File dirFile) {
        List<String> resultFile = new ArrayList<>();
        File[] files = dirFile.listFiles();
        // 判断目录下是不是空的
        if (files == null) {
            return resultFile;
        }
        for (File f : files) {
            // 判断是否文件夹
            if (f.isDirectory()) {
                resultFile.add(f.getPath());
                // 调用自身,查找子目录
                DirAll(f);
            } else {
                resultFile.add(f.getPath());
            }
        }
        return resultFile;

    }


    //遍历路径下所有的文件
    public static ArrayList<File> refreshFileList(String strPath) {
        // 存储文件列表
        ArrayList<File> fileList = new ArrayList<>();
        // 创建文件
        File dir = new File(strPath);
        // 获取当前路径下的所有文件
        File[] files = dir.listFiles();
        // 判断文件数组是否为空
        if (null == files) {
            return null;
        }
        // 循环遍历所有文件
        for (int i = 0, size = files.length; i < size; i++) {
            // 如果是文件夹
            if (files[i].isDirectory()) {
                // 遍历此路径，执行此方法
                ArrayList<File> refreshFileList = refreshFileList(files[i].getAbsolutePath());
                if (null != refreshFileList) {
                    fileList.addAll(refreshFileList);
                }
            } else {
                // 添加到文件列表
                fileList.add(files[i]);
            }
        }
        return fileList;
    }

    //遍历删除文件夹下面的指定格式的file文件
    public static void deleteAllInnerFilesAndDirs(String filePath) {

        File file = new File(filePath);
        boolean isDirectory = file.isDirectory();
        if (isDirectory) {
            String[] files = file.list();
            File[] listFiles = file.listFiles();
            for (String f : files) {
                String afterPointLetter = f.substring(f.lastIndexOf(".") + 1, f.length());
                if (forbidFormat(afterPointLetter)) {
                    System.out.println("d:\\movie\\" + f);
                    File deleteFile = new File(filePath + f);
                    if (deleteFile.exists()) {
                        deleteFile.delete();
                    }
                }
            }
        } else {
            if (file.isFile()) {
                file.delete();
            }
        }

    }

    public static boolean forbidFormat(String threeLetter) {
        List<String> fileFormat = new ArrayList<String>();
        fileFormat.add("jpg");
        fileFormat.add("avi");
        if (fileFormat.contains(threeLetter)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除所有文件和目录
     *
     * @param path
     */
    public static void deleteAllFilesAndDirs(String path) {

        File createFile = new File(path);
        File[] listFiles = createFile.listFiles();
        for (File file : listFiles) {
            if (file.isFile()) {
                file.delete();
            } else {
                deleteAllFilesAndDirs(file.toString());
                file.delete();
            }
        }
        System.out.println("删除完成！");
    }

    public static void deleteFolder(File dir) {

        File dirFile[] = dir.listFiles();
        for (int i = 0; i < dirFile.length; i++) {
            if (dirFile[i].isDirectory()) {
                deleteFolder(dirFile[i]);
            }
            dirFile[i].delete();
        }
    }


    /**
     * 递归查看文件和目录
     * https://developer.aliyun.com/article/716235?spm=a2c6h.14164896.0.0.a1515eb3kn0XMg
     *
     * @param path
     */
    public static void showAllFilesAndDirs(String path) {
        List fileList = new ArrayList();
        List fodeList = new ArrayList();

        File dirFile = new File(path);
        File[] files = dirFile.listFiles();
        if (null == files) {
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("目录》》》" + file);
                fodeList.add(file.toString());
                showAllFilesAndDirs(file.getAbsolutePath());

            } else {
                System.out.println("文件》》》" + file);
                fileList.add(file.toString());
            }
        }
        System.out.println("fileList : " + fileList.toString());
        System.out.println("fodeList : " + fodeList.toString());
    }

    //复制文件夹
    private static void copyFolder(File srcFile, File desFile) throws IOException {
        if (srcFile.isDirectory()) {
            //是文件夹,首先在目标位置创建同名文件夹，然后遍历文件夹下的文件，进行递归调用copyFolder函数
            File newFolder = new File(desFile, srcFile.getName());
            newFolder.mkdir();
            File[] fileArray = srcFile.listFiles();
            for (File file : fileArray) {
                copyFolder(file, newFolder);
            }
        } else {
            //是文件，直接copy到目标文件夹
            File newFile = new File(desFile, srcFile.getName());
            copyFile(srcFile, newFile);
        }
    }

    //复制文件到指定位置
    private static void copyFile(File srcFile, File newFile) throws IOException {
        //复制文件到指定位置
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
        byte[] b = new byte[1024];
        Integer len = 0;
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bis.close();
        bos.close();
    }

    /*判断文件是否存在*/
    public static boolean isExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /*判断是否是文件夹*/
    public static boolean isDir(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file.isDirectory();
        } else {
            return false;
        }
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */

    public static boolean delete(String fileName) {
        try {
            File sourceFile = new File(fileName);
            if (sourceFile.isDirectory()) {
                for (File listFile : sourceFile.listFiles()) {
                    delete(listFile.getAbsolutePath());
                }
            }
            return sourceFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;

    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
//       String base64=  imageUrlToBase64("http://117.187.230.142:9000/auth/20221226774CDB018B7049FD87B336240ACDA356.jpg");
//        String code1 = "data:Image/" + "png" + ";base64," +base64;
//        Integer len1 = imageSize(code1);
//        String code = "data:Image/" + "png" + ";base64," +resizeImageTo40K( base64);
//        Integer len = imageSize(code);
//        System.out.println();
    }




}